package com.luo.demo.component;

import com.luo.demo.config.ApplicationConfig;
import lombok.Data;
import org.springframework.stereotype.Component;
import redis.clients.jedis.ShardedJedis;
import redis.clients.jedis.ShardedJedisPool;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

/**
 * @author xiangnan
 * @date 2018/1/25 18:07
 */
@Data
@Component
public class RedisClient {

    @Resource
    private ApplicationConfig applicationConfig;

    private ShardedJedisPool jedisPool;

    @PostConstruct
    public void init() {
        this.jedisPool = new ShardedJedisPool(applicationConfig.getPoolConfig(),
                applicationConfig.getJedisShardInfoList());
    }

    public ShardedJedis getJedis() {
        try {
            return jedisPool.getResource();
        } catch (Exception e) {
            e.printStackTrace();

            this.jedisPool.destroy();
            init();
            return jedisPool.getResource();
        }
    }

}
